<template>
	<div ref="chartRef" class="echartsClass"></div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts'
import { onBeforeUnmount, onMounted, ref } from 'vue'

const props = defineProps<{
	data: []
}>()

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
	if (!chartRef.value) {
		return
	}
	chartInstance?.dispose()
	chartInstance = echarts.init(chartRef.value)
	updateChart()
	window.addEventListener('resize', handleChartResize)
}

const chartData = {
	xAxisData: ['楼小航', '张思麦', 'xuqi', 'qinshuang', 'liyang'],
	seriesData: [12, 20, 20, 23, 24]
}

const updateChart = () => {
	if (!chartInstance) {
		return
	}
	const option = {
		title: {
			text: '逾期项目负责人分布'
		},
		grid: {
			left: '100px' // 为 y 轴留出足够宽度
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: { type: 'shadow' }
		},
		xAxis: {
			type: 'value'
		},
		yAxis: {
			type: 'category',
			data: chartData.xAxisData
		},
		series: [
			{
				name: '负责人',
				type: 'bar',
				data: chartData.seriesData,
				itemStyle: {
					color: params => (params.value > 20 ? '#ff6384' : '#36a2eb')
				},
				label: {
					show: true,
					position: 'right'
				},
				// 点击事件
				onClick: params => {
					alert(`查看 ${params.name} 的逾期详情`)
				}
			}
		]
	}

	chartInstance.setOption(option)
}

const handleChartResize = () => {
	chartInstance?.resize()
}

const cleanupChart = () => {
	window.removeEventListener('resize', handleChartResize)
	chartInstance?.dispose()
}

onBeforeUnmount(() => {
	cleanupChart()
})

onMounted(() => {
	initChart()
})
</script>
<style lang="scss" scoped>
.echartsClass {
	width: 550px;
	height: 400px;
}
</style>
